<?
Session_Start();		

//https://blog.csdn.net/fmisk/article/details/80428817


$host = "127.0.0.1:4306";
$username = "root";
$password = "a123456";
$dbname = "vue";
$con=mysqli_connect($host, $username,$password, $dbname);
//$con->set_charset('utf8'); //设置查询结果编码

if (mysqli_connect_errno($con))
{
	echo "连接 MySQL 失败: " . mysqli_connect_error();
}


function rlog($action){
    global $con;
   
    $curDate =date('Y-m-d H:i:s');
	$sql="INSERT INTO log(sj,user,action,ip)VALUES('".$curDate."','user','".$action."','".getIP()."')";
	mysqli_query($con,$sql);
}


// 数组 包含 字符串
function contains_($str, $num)
{
	//arr := strings.Split(str, ",") //角色权限列表（数组）
	$arr=explode(',',$str);
	for($x=0;$x<count($arr);$x++)
	{
		if($arr[$x]==$num)
			return true;
	}

	return false;
}


// 导出数据库备份
function export_backup() {

    $backup_file =date('Y-m-d-H:i:s');

    $sql="mysqldump -h 127.0.0.1 -P 4306 -uroot -pa123456 vue > /home/500G/wwwroot/vue-el/databack/".$backup_file.".sql";
	exec($sql,$out,$status);
    return $status;
}

//-----------------token jwt-----------------------------
require '../vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


function getToken($id){		// user.php login() 使用！
    $key = 'example_key';
    $payload = [
        'iss' => $id, 					//签发者
        'aud' => 'Vue Background Management System',	//接收jwt的一方
        'iat' => time(),   				//什么时候签发的
        'exp' => time()+3600*8  		//过期时间 8小时  3600*8
    ];

    $jwt = JWT::encode($payload, $key, 'HS256');
    return $jwt;
}

function refreshToken($id){		// user.php login() 使用！
    $key = 'example_key';
    $payload = [
        'iss' => $id, 					//签发者
        'aud' => 'Vue Background Management System',	//接收jwt的一方
        'iat' => time(),   				//什么时候签发的
        'exp' => time()+60  		//过期时间 24小时
    ];

    $jwt = JWT::encode($payload, $key, 'HS256');
    return $jwt;
}

function verifyToken($token){
    $key = 'example_key';
        
	if(!strstr($_SERVER["REQUEST_URI"],"login.html")){	
	
		$token = $_SERVER['HTTP_AUTHORIZATION'];
		$token=str_replace("Bearer ","",$token);
		return $decoded = JWT::decode($token, new Key($key, 'HS256'));
	}
}

function verifyToken1($token){
    $key = 'example_key';
        
	if(!strstr($_SERVER["REQUEST_URI"],"login.html")){	

		$str=$decoded = JWT::decode($token, new Key($key, 'HS256'));	
        $sql="SELECT * FROM juser,user  where user.juser_id=juser.id and user.id='".$str->iss."'";
        $rs =  mysqli_query($con,$sql);
        $row = $rs->fetch_assoc();
		$data['code'] = '200';
        $data['message'] = $row;
        return $data;

		// $token = $_SERVER['HTTP_AUTHORIZATION'];
		// $token=str_replace("Bearer ","",$token);
	
		// $str=$decoded = JWT::decode($token, new Key($key, 'HS256'));
		// //return $str->iss;
		// //return $str;
	
        // $sql="SELECT * FROM juser,user  where user.juser_id=juser.id and user.id='".$str->iss."'";
        // $rs =  mysqli_query($con,$sql);
        // //$row = $rs->fetch_assoc();
		// $data['code'] = '200';
        // $data['message'] = $row;
        // return $sql;
	}
}




//PHP后端token生成与校验
//https://blog.csdn.net/weixin_41850404/article/details/124420150
function CreateToken($userid) {
    $time = time();
    $end_time = time() + 3600;	
    $info = $userid . '.' . $time . '.' . $end_time; //设置token过期时间为一天  86400
    //根据以上信息信息生成签名（密钥为 SIGNATURE 自定义全局常量)
    $signature = hash_hmac('md5', $info, "SIGNATURE");
    //最后将这两部分拼接起来，得到最终的Token字符串
    return $token = $info . '.' . $signature;
}
 
//检查token  (js->comm.js)
function CheckToken($token) {
    if (!isset($token) || empty($token)) {
        $data['code'] = '401';
        $data['message'] = '非法请求';
        return $data;
    }
    //对比token
    $explode = explode('.', $token); //以.分割token为数组
    if (!empty($explode[0]) && !empty($explode[1]) && !empty($explode[2]) && !empty($explode[3])) {
        $info = $explode[0] . '.' . $explode[1] . '.' . $explode[2]; //信息部分
        $true_signature = hash_hmac('md5', $info, "SIGNATURE"); //正确的签名
        if (time() > $explode[2]) {
            $data['code'] = '401';
            $data['message'] = 'Token已过期,请重新登录';
            return $data;
        }
        if ($true_signature == $explode[3]) {
            $data['code'] = '200';
            $data['message'] = 'Token合法';
            return $data;
        } else {
            $data['code'] = '401';
            $data['message'] = 'Token不合法';
            return $data;
        }
    } else {
        $data['code'] = '401';
        $data['message'] = 'Token不合法';
        return $data;
    }
}


function getIP(){
    $client_ip='';
    if (isset($_SERVER))
    {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
        {
            //优先使用  HTTP_X_FORWARDED_FOR，此值是一个逗号分割的多个IP
          //注意：我这里没做处理，是因为运维在入口处禁止了伪造请求头，HTTP_X_FORWARDED_FOR是可信的，不能代表所有业务场景
            //todo 没有禁止伪造请求头下的特殊处理
            $ipStr   = $_SERVER["HTTP_X_FORWARDED_FOR"];
            $ipArr = explode(',',$ipStr);
            $client_ip = isset($ipArr[0])?$ipArr[0]:'';
        }
        else if (isset($_SERVER["HTTP_CLIENT_IP"]))
        {
            $client_ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        else
        {
            $client_ip = $_SERVER["REMOTE_ADDR"];
        }
    }
    //过滤无效IP
    if(filter_var($client_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false || filter_var($client_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false){
        return $client_ip;
    }else{
        return $_SERVER["REMOTE_ADDR"];
    }    
}


?>